package com.front.teacher.teacherapp.base;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.SurfaceHolder;
import android.widget.Toast;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2016/8/12.
 * 注意所有定义code的地方，基类里是从1000-2000，继承时注意不要使用这个区间，避免冲突
 */
public abstract class PermissionsActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    private static final String TAG = "syzt.PermActivity";

    //相机需要的权限
    protected static String[] permissionsCamera = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //easyPermissions中打开相机的回调的requestcode定义
    private static final int EasyPermCamera = 1000;
    //相机预览的容器
    private SurfaceHolder surfaceHolderCamera;

    //相机对象
    private Camera mCamera = null;

    /**
     * 用户对请求作出响应后的回调
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(Arrays.equals(permissions, permissionsCamera)) {
            EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
            this.openCameraAction();
        } else {
            EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        }
    }

    /**
     * 获得权限后，执行的操作
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if(requestCode == EasyPermCamera) {
            openCameraAction();
        }
    }

    /**
     * 权限被拒绝时
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if(requestCode == EasyPermCamera) {
            //Toast.makeText(this, "相机权限被拒绝", 1).show();
            this.doCameraPermissionsDeniedTips();
        }
    }

    /**
     * 相机权限被拒绝时的提示
     */
    protected void doCameraPermissionsDeniedTips() {
        Log.w(TAG, "相机权限被拒绝");
        // TODO 需要完善，1：最佳方案最好能根据机型，自动的打开相应的权限设置；
        // 2：给出设置的方式提示，做一个新的activity进行设置
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setMessage("需要摄像头权限");
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                Intent intent = new Intent(Settings.ACTION_APPLICATION_SETTINGS);
//                startActivity(intent);
            }
        });
//        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//            }
//        });
        dialog.show();
    }

    /**
     * 封装打开相机的实现
     */
    private void openCameraAction() {
        if(null == mCamera) {
            if(null == surfaceHolderCamera) {
                Log.w(TAG, "surfaceHolder为空，相机可能无法正常显示预览");
            }
            try {
                mCamera = Camera.open();
                if(null != surfaceHolderCamera) {
                    mCamera.setPreviewDisplay(surfaceHolderCamera);
                }
                Camera.Parameters parameters = mCamera.getParameters();
                //mCamera.setDisplayOrientation(90);
                mCamera.setParameters(parameters);
                mCamera.startPreview();
            } catch (Exception e) {
                //e.printStackTrace();
                Log.e(TAG, "打开相机出错了", e);
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    //小于6.0出错了，就认为是没有权限
                    doCameraPermissionsDeniedTips();
                } else if(!EasyPermissions.hasPermissions(this, permissionsCamera)) {
                    doCameraPermissionsDeniedTips();
                }
            }
        }
    }

    /**
     * 打开相机
     */
    protected void openCamera() {
        if (EasyPermissions.hasPermissions(this, permissionsCamera)) {
            openCameraAction();
        } else {
            EasyPermissions.requestPermissions(this, "需要使用摄像头", 0x23, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
    }

    /**
     * 设置相机预览的容器
     * @param surfaceHolder
     */
    protected void setCameraSurfaceHolder(SurfaceHolder surfaceHolder) {
        this.surfaceHolderCamera = surfaceHolder;
    }

    /**
     * 获得相机对象
     * @return
     */
    protected Camera getCamera() {
        return mCamera;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.releaseCamera();
    }

    /**
     * 释放相机资源
     */
    protected void releaseCamera() {
        if(null != mCamera) {
            mCamera.release();
            mCamera = null;
        }
    }

}
